package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.constants.CommonConstant;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.response.MathChaPlan;
import com.xmy.cultivate.entity.response.TidyRs;
import com.xmy.cultivate.respons.QyWeChartPushRs;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 试岗 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2024-12-08
 */
@Controller
@RestController
@RequestMapping("/api/tryJob")
@Scope("prototype")
public class TryJobController extends BaseController{
    @Autowired
    ITryJobService iTryJobService;
    @Autowired
    IRecruitCertificateService iRecruitCertificateService;
    @Autowired
    IRecruitService iRecruitService;
    @Autowired
    IDistrictService iDistrictService;
    @Autowired
    IRecruitAuditLogService iRecruitAuditLogService;
    @Autowired
    IStaffService iStaffService;
    @Autowired
    IRecruitImageService iRecruitImageService;
    @Autowired
    IRecruitExperienceService iRecruitExperienceService;
    @Autowired
    IOrganizationService iOrganizationService;
    @Autowired
    ISchoolNeedsService iSchoolNeedsService;
    @Autowired
    ITryJobAllocationService iTryJobAllocationService;
    @Autowired
    IPermissionSchoolTeacherService iPermissionSchoolTeacherService;

    @Autowired
    IMqPushService iMqPushService;

    @Autowired
    IRecruitPushLogService iRecruitPushLogService;

    @Autowired
    IQyWeChartPushService iQyWeChartPushService;

    @Autowired
    IAllotTeacherWheelService iAllotTeacherWheelService;

    @Autowired
    IQuarterService iQuarterService;
    @Autowired
    IEstimateDetailsService iEstimateDetailsService;
    @Autowired
    IStationNeedsService  iStationNeedsService;

    @Autowired
    IDepartmentService iDepartmentService;

    @Autowired
    ITrialFormService iTrialFormService;

    @Autowired
    IAllotAreaSetService iAllotAreaSetService;

    @GetMapping("/getAreaList")
    public Result getAreaList(){
        List<Area> areaList = iAllotAreaSetService.getAllotAreaList();
        return new Result(Code.OK, areaList, "获取成功");
    }




    /**
     * 试岗数据统计
     * @param startDate
     * @param endDate
     */
    @RequestMapping("/tryJobDataCount")
    public Result tryJobDataCount(
            @RequestParam(value = "startDate",required = false) String startDate,
            @RequestParam(value = "endDate",required = false) String endDate
    ){
        QueryWrapper<TryJob> queryWrapper = new QueryWrapper<>();
        //判断开始时间不能为空
        if (StringUtils.isBlank(startDate)){
            return new Result(Code.OK, null, "请选择开始时间");
        }
        //判断结束时间不能为空
        if (StringUtils.isBlank(endDate)){
            return new Result(Code.OK, null, "请选择结束时间");
        }
        HashMap<String, Object> map = new HashMap<>();

        Long adminIdAccount = this.adminId;
        String schoolId = null;
        String subjectId = null;
        // 判断是否是超级管理员
        //1667155660271255552L人事主管
        if (adminIdAccount == 1568138350324350975L || adminIdAccount == 1667155660271255552L) {
            schoolId = null;
            subjectId = null;
        } else {
            // 判断是否为permission_school_teacher下的老师

//            List<String> schoolIdByTeacherId = iPermissionSchoolTeacherService.getSchoolIdByTeacherId(String.valueOf(adminIdAccount));
            List<PermissionSchoolTeacher> permissionSchoolTeacherByTeacherId = iPermissionSchoolTeacherService.getPermissionSchoolTeacherByTeacherId(String.valueOf(adminIdAccount));
            List<String> schoolIdByTeacherId = new ArrayList<>();
            List<String> subjectsIdByTeacherId = new ArrayList<>();

            for (PermissionSchoolTeacher permissionSchoolTeacher : permissionSchoolTeacherByTeacherId) {
                schoolIdByTeacherId.add(String.valueOf(permissionSchoolTeacher.getSchoolId()));
                subjectsIdByTeacherId.add(String.valueOf(permissionSchoolTeacher.getSubjectsId()));
            }
            if (schoolIdByTeacherId != null && schoolIdByTeacherId.size()>0 && subjectsIdByTeacherId != null && subjectsIdByTeacherId.size()>0){
                schoolId = String.join(",", schoolIdByTeacherId);
                subjectId = String.join(",", subjectsIdByTeacherId);

            } else {
                schoolId = null;
                subjectId = null;

            }
        }


        //获取未点评总数
        Long tryJobCount = iTryJobService.count(
                new QueryWrapper<TryJob>()
                        .eq("pass_type",0)
                        .eq("is_arrive_job", 0)
                        .in(StringUtils.isNotBlank(schoolId),"school_id", schoolId)
                        .in(StringUtils.isNotBlank(subjectId),"subjects_id", subjectId)
                        .between("try_date", startDate, endDate));
        //获取通过总数
        Long tryJobPassCount = iTryJobService.count(
                new QueryWrapper<TryJob>()
                        .eq("pass_type",1)
                        .eq("is_arrive_job", 0)
                        .in(StringUtils.isNotBlank(schoolId),"school_id", schoolId)
                        .in(StringUtils.isNotBlank(subjectId),"subjects_id", subjectId)
                        .between("try_date", startDate, endDate));
        //获取未通过总数
        Long tryJobNoPassCount = iTryJobService.count(
                new QueryWrapper<TryJob>()
                        .eq("pass_type",2)
                        .eq("is_arrive_job", 0)
                        .in(StringUtils.isNotBlank(schoolId),"school_id", schoolId)
                        .in(StringUtils.isNotBlank(subjectId),"subjects_id", subjectId)
                        .between("try_date", startDate, endDate));
        //获取待点评总数
        Long tryJobWaitCount = iTryJobService.count(
                new QueryWrapper<TryJob>()
                        .eq("pass_type",0)
                        .in(StringUtils.isNotBlank(schoolId),"school_id", schoolId)
                        .in(StringUtils.isNotBlank(subjectId),"subjects_id", subjectId)
                        .and(wrapper -> wrapper.eq("try_satisficing", 0).or().eq("is_appraisal", 0))
                        .between("try_date", startDate, endDate));
        //获取是否通过总数
        Long tryJobIsPassCount = iTryJobService.count(
                new QueryWrapper<TryJob>()
                        .eq("pass_type",0)
                        .eq("is_appraisal",1)
                        .in(StringUtils.isNotBlank(schoolId),"school_id", schoolId)
                        .in(StringUtils.isNotBlank(subjectId),"subjects_id", subjectId)
                        .in("try_satisficing",1,2,3)
                        .between("try_date", startDate, endDate));
        //获取未到岗总数
        Long tryJobNoArriveCount = iTryJobService.count(
                new QueryWrapper<TryJob>()
                        .eq("pass_type",0)
                        .in(StringUtils.isNotBlank(schoolId),"school_id", schoolId)
                        .in(StringUtils.isNotBlank(subjectId),"subjects_id", subjectId)
                        .eq("is_arrive_job",1)
                        .between("try_date", startDate, endDate));
        map.put("tryJobCount",tryJobCount);
        map.put("tryJobPassCount",tryJobPassCount);
        map.put("tryJobNoPassCount",tryJobNoPassCount);
        map.put("tryJobWaitCount",tryJobWaitCount);
        map.put("tryJobIsPassCount",tryJobIsPassCount);
        map.put("tryJobNoArriveCount",tryJobNoArriveCount);
        return new Result(Code.OK, map, Code.GET_OK_MSG);
    }

    /**
     * 试岗列表
     * @param startDate
     * @param endDate
     * @param name
     * @param type
     * @param isReview
     * @param pageNum
     * @param pageSize
     */
    @GetMapping("/tryJobList")
    public Result tryJobList(@RequestParam(value = "startDate",required = false) String startDate,
                             @RequestParam(value = "endDate",required = false) String endDate,
                             @RequestParam(value = "name",required = false) String name,
                             @RequestParam(value = "type",defaultValue = "0") String type,  // 0待点评   1通过  2未通  3未到岗
                             @RequestParam(value = "isReview",defaultValue = "0") String isReview,  // 0待点评  1是否通过
                             @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                             @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize){

        IPage<TryJob> page = new Page<>( pageNum, pageSize);
        Long adminIdAccount = this.adminId;
        String schoolId = null;
        String subjectId = null;
        // 判断是否是超级管理员
        //1667155660271255552L人事主管
        if (adminIdAccount == 1568138350324350975L || adminIdAccount == 1667155660271255552L) {
            schoolId = null;
            subjectId = null;
        } else {
            // 判断是否为permission_school_teacher下的老师
//            List<String> schoolIdByTeacherId = iPermissionSchoolTeacherService.getSchoolIdByTeacherId(String.valueOf(adminIdAccount));
            List<PermissionSchoolTeacher> permissionSchoolTeacherByTeacherId = iPermissionSchoolTeacherService.getPermissionSchoolTeacherByTeacherId(String.valueOf(adminIdAccount));
            List<String> schoolIdByTeacherId = new ArrayList<>();
            List<String> subjectsIdByTeacherId = new ArrayList<>();

            for (PermissionSchoolTeacher permissionSchoolTeacher : permissionSchoolTeacherByTeacherId) {
                schoolIdByTeacherId.add(String.valueOf(permissionSchoolTeacher.getSchoolId()));
                subjectsIdByTeacherId.add(String.valueOf(permissionSchoolTeacher.getSubjectsId()));
            }
            if (schoolIdByTeacherId != null && schoolIdByTeacherId.size()>0 && subjectsIdByTeacherId != null && subjectsIdByTeacherId.size()>0){
                schoolId = String.join(",", schoolIdByTeacherId);
                subjectId = String.join(",", subjectsIdByTeacherId);

            }
            else {
                schoolId = null;
                subjectId = null;

            }
        }
        List<TryJob> tryJobList = iTryJobService.queryTryJobList(page,startDate,endDate,type,name, schoolId,subjectId);
//        Map<Long, Map<String, Object>> resultMap = new HashMap<>();
        List<HashMap<String, Object>> list = new ArrayList<>();
        //判断tryJobList
        if (tryJobList!=null || tryJobList.size()>0){
            for (TryJob tryJob : tryJobList) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("id",tryJob.getId());
                map.put("tryDate",tryJob.getTryDate());
                map.put("subjectsId",tryJob.getSubjectsId());
                String  campus = iOrganizationService.getById(tryJob.getSchoolId()).getName();
                Recruit recruit = iRecruitService.getById(tryJob.getRecruitId());
                if (recruit!=null){
                    map.put("headImage",recruit.getHeadImage());
                    map.put("name",recruit.getName());              //姓名
                    map.put("phone",recruit.getPhone());            //手机号
                    map.put("age",recruit.getAge());                 //年龄
                    map.put("marriage",recruit.getMarriage());       //婚姻
                    map.put("education",recruit.getEducation());      //学历
                    map.put("stations",recruit.getStations());         //岗位意向
                    map.put("schoolName",recruit.getSchoolName());  //大学名称
                    map.put("major",recruit.getMajor());             //专业
                    map.put("recruitId",recruit.getId());
                    if (recruit.getEnterType() == 2) {
                        map.put("recruitFileUrl", recruit.getRecruitFileUrl());
                    }
                    map.put("enterType", recruit.getEnterType());
                }

                QueryWrapper<EstimateDetails> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("recruit_id", recruit.getId());
                queryWrapper.eq("type", 2);
                long count = iEstimateDetailsService.count(queryWrapper);
                Integer evaluate = 0;//0未评价 1已评价
                if (count > 0){
                    evaluate = 1;
                }
                map.put("evaluate",evaluate);
                String departmentName = null;
                if (tryJob.getDepartmentType() != null){
                    if (tryJob.getDepartmentType().equals(2) && tryJob.getDepartmentName() != null){
                        departmentName = tryJob.getDepartmentName();
                    }
                }
                if (departmentName != null){
                    map.put("campus",departmentName);   //显示部门名称
                }else {
                    map.put("campus",campus);   //校区
                }

                map.put("passType",tryJob.getPassType());
                map.put("trySatisficing",tryJob.getTrySatisficing());
                map.put("isAppraisal",tryJob.getIsAppraisal());
                map.put("score",tryJob.getScore());
                map.put("comment",tryJob.getTryComment());
                map.put("smallScore",tryJob.getSmallScore());
                map.put("isArriveJob",tryJob.getIsArriveJob());
                list.add(map);
            }
        }
        return new Result(Code.OK, new PageResult<>(list, page.getTotal(), page.getPages()), Code.GET_OK_MSG);
    }

    @PostMapping("/addTryJob")
    @Transactional
    public Result addTryJob(@RequestBody TryJob tryJob) {
        Quarter quarterNow = iQuarterService.getNowQuarter();
        tryJob.setYearPart(quarterNow.getYearPart());
        tryJob.setQuarterNum(quarterNow.getNum());
        tryJob.setStationNeedsId(tryJob.getStationId());//升级使用原来字段
        if (tryJob.getRecruitId() == null){
            return new Result(Code.ERROR,"","简历id不能为空，分配失败，请与智能部联系");
        }
        Recruit recruit = iRecruitService.getById(tryJob.getRecruitId());
        if (Objects.isNull(recruit)){
            return new Result(Code.ERROR,"","简历不存在，分配失败，请与智能部联系");
        }
        StationNeeds stationNeeds = iStationNeedsService.getById(tryJob.getStationNeedsId());
        if (Objects.isNull(stationNeeds)){
            return new Result(Code.ERROR,"","分配岗位不能为空");
        }
        tryJob.setStationId(stationNeeds.getStationId());

        boolean save = iTryJobService.save(tryJob);
        if (save){
            boolean isUpdateYetNum = true;
            //校区岗位
            if (stationNeeds.getType() == 1){
                //判断是校区招，还是部门招
                Integer personType = iRecruitService.getPersonType(recruit.getId());
                if (personType.equals(1)) {
                    Staff inviterInfo = iAllotTeacherWheelService.getStaffSchoolInfo(quarterNow.getYearPart(),quarterNow.getNum(),recruit.getInviterId());
                    if (Objects.nonNull(inviterInfo)) {
                        if (inviterInfo.getSchoolId()!=null){
                            if (tryJob.getSchoolId().equals(inviterInfo.getSchoolId())){
                                isUpdateYetNum = false;
                            }
                        }
                    }
                }
            }
            //是否更新使用次数
            if (isUpdateYetNum){
                UpdateWrapper<AllotTeacherWheel> wrapper = new UpdateWrapper<>();
                wrapper.eq("school_id",tryJob.getSchoolId());
                //wrapper.eq("year_part",quarterNow.getYearPart());
                //wrapper.eq("quarter_num",quarterNow.getNum());
                wrapper.eq("station_id",stationNeeds.getStationId());
                wrapper.eq("subjects_id",stationNeeds.getSubjectsId());
                if (stationNeeds.getType() == 1){
                    if (recruit.getAreaId() != null) {
                        //wrapper.eq("area_id", recruit.getAreaId());
                    }
                }
                //wrapper.set("yet_num",1);
                wrapper.setSql("yet_num = yet_num + 1");
                iAllotTeacherWheelService.update(wrapper);
            }



            //原先分配给校长调整为分配主管
            QueryWrapper<PermissionSchoolTeacher> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("school_id",tryJob.getSchoolId());
            queryWrapper.eq("type",1);
            queryWrapper.eq("subjects_id",tryJob.getSubjectsId());
            queryWrapper.eq("deleted",0);
//            queryWrapper.eq("position_type",1);
            queryWrapper.eq("position_type",3);
            queryWrapper.last("limit 1");
            PermissionSchoolTeacher permissionSchoolTeacher = iPermissionSchoolTeacherService.getOne(queryWrapper);

            if (permissionSchoolTeacher!=null){

                Staff staff = iStaffService.getById(permissionSchoolTeacher.getTeacherId());


                if (staff!=null) {
                    if (StringUtils.isNotBlank(staff.getQyWecharId())) {
                        //推送内容
                        QyWeChartPushRs qyWeChartPushRs = new QyWeChartPushRs();
                        qyWeChartPushRs.setToUser(staff.getQyWecharId());
                        qyWeChartPushRs.setTitle("分配到校区");
                        qyWeChartPushRs.setContent("您的校区有新的试岗人员:" + recruit.getName());
                        qyWeChartPushRs.setRemark("请及时查看");
                        qyWeChartPushRs.setDateTime(LocalDate.now().toString());
                        qyWeChartPushRs.setLinkUrl(CommonConstant.teacherWebUrl);
                        //推送到企业微信
                        iMqPushService.pushContentForQyWeChar(qyWeChartPushRs);

                        RecruitPushLog log = new RecruitPushLog();
                        log.setRecruitId(tryJob.getRecruitId());
                        log.setType(2); // 2给校长推送分配到校区
                        log.setPushStaffId(permissionSchoolTeacher.getTeacherId());
                        log.setStatus(1);  //1已推送
                        iRecruitPushLogService.save(log);
                    }else {

                        RecruitPushLog log = new RecruitPushLog();
                        log.setRecruitId(tryJob.getRecruitId());
                        log.setType(2); // 2给校长推送分配到校区
                        log.setPushStaffId(permissionSchoolTeacher.getTeacherId());
                        log.setStatus(0); //0未推送
                        log.setRemark(recruit.getName()+"分配给"+tryJob.getSchoolId()+"时"+permissionSchoolTeacher.getTeacherId()+"qyWecharId为空");
                        iRecruitPushLogService.save(log);
                    }
                }

            }

            return new Result(Code.OK, "", "分配成功");
        }
        return new Result(Code.ERROR,"","分配失败");
    }

    @PostMapping("/refuseAllocation")
    public Result refuseAllocation(@RequestBody TryJobAllocation tryJobAllocation) {
        tryJobAllocation.setAuditId(this.adminId);
        boolean save = iTryJobAllocationService.save(tryJobAllocation);
        if (save){
            return new Result(Code.OK, "", "操作成功");
        }
        return new Result(Code.ERROR,"","操作失败");

    }

    /**
     * 获取分配校区列表
     * @param stationNeedsId 岗位id
     * @param recruitId 简历id
     * @param areaId 区域id
     * @return
     */
    @GetMapping("/getAllocateSchoolList")
    public Result getAllocateSchoolList(@RequestParam(value = "stationNeedsId",required = false) String stationNeedsId,
                                        @RequestParam(value = "recruitId",required = false) String recruitId,
                                        @RequestParam(value = "areaId",required = false) Long areaId
                                        ) {

        if (StringUtils.isEmpty(recruitId)){
            return new Result(Code.ERROR,"","简历id不能为空，请与智能部联系");
        }

        if (StringUtils.isEmpty(stationNeedsId)){
            return new Result(Code.ERROR,"","岗位id不能为空，请与智能部联系");
        }

        StationNeeds stationNeeds = iStationNeedsService.getById(stationNeedsId);

        Quarter nowQuarter = iQuarterService.getNowQuarter();
        Integer quarterNum = nowQuarter.getNum();
        Integer yearPart = nowQuarter.getYearPart();
        Recruit recruit = iRecruitService.getById(recruitId);
        if (areaId == null){
            areaId = recruit.getAreaId();
        }
        Long allotSchoolId = iAllotTeacherWheelService.getAllotSchoolId(yearPart, quarterNum,Long.parseLong(recruitId), Long.parseLong(stationNeedsId), areaId,recruit.getInviterId());
        if (allotSchoolId==null){
            //return new Result(Code.ERROR,"","无分配的校区");
        }
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String,Object> map;
        if (stationNeeds.getType().equals(2)){
            areaId = null;//部门岗区域设置为空
        }
        List<TidyRs> tidyRsList = iSchoolNeedsService.getAllNeedsSchoolForLess(stationNeeds.getStationId(),stationNeeds.getSubjectsId(),areaId);
        for (TidyRs tidyRs : tidyRsList){
            map = new HashMap<>();
            map.put("id",tidyRs.getId());
            map.put("schoolName",tidyRs.getName());
            map.put("subjectsId","");
            map.put("stationId","");
            map.put("sort","");
            list.add(map);
        }
        //allotSchoolId = null;
        Map<String,Object> mapResult = new HashMap<>();
        mapResult.put("list",list);
        mapResult.put("allotSchoolId",allotSchoolId);

        return new Result(Code.OK, mapResult, Code.GET_OK_MSG);

    }


/*    @GetMapping("/getAllocateSchoolList")
    public Result getAllocateSchoolList(@RequestParam(value = "stationId",required = false) String stationId) {

        List<TryJob> allocateSchoolList = iTryJobService.getAllocateSchoolList(stationId);
        List<HashMap<String, Object>> list = new ArrayList<>();
        if (allocateSchoolList!=null && !allocateSchoolList.isEmpty()){
            for (TryJob tryJob : allocateSchoolList) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("id",tryJob.getSchoolId());
                map.put("schoolName",tryJob.getSchoolName());
                map.put("subjectsId",tryJob.getSubjectsId());
                map.put("stationId",tryJob.getStationId());
                map.put("sort",tryJob.getSort());
                list.add(map);
            }
            return new Result(Code.OK, list, Code.GET_OK_MSG);
        }
        return new Result(Code.ERROR,"","无分配的校区");

    }*/

    /**详情
     *
     * @param tryJobId
     * @return
     */
    @GetMapping("/tryJobDetail")
    public Result tryJobDetail(@RequestParam(value = "tryJobId",required = true) Long tryJobId) {
        TryJob tryJob = iTryJobService.getById(tryJobId);
        if (tryJob == null){
            return new Result(Code.ERROR,"","数据不存在");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("tryDate",tryJob.getTryDate());   //试岗时间
        String  campus = iOrganizationService.getById(tryJob.getSchoolId()).getName();
        map.put("campus",campus);    //分配校区
//        map.put("passType",tryJob.getPassType());
        map.put("trySatisficing",tryJob.getTrySatisficing());
        map.put("isAppraisal",tryJob.getIsAppraisal());
        map.put("allocateTime",tryJob.getCreatedAt());   //分配时间
        map.put("tryAuditDate",tryJob.getTryAuditDate()); //试岗点评时间
        map.put("notArriveReason",tryJob.getNotArriveReason()); //未到岗原因
        map.put("isArriveJob",tryJob.getIsArriveJob());
        //试岗评语
        map.put("tryComment",tryJob.getTryComment());
        Recruit recruit = iRecruitService.getById(tryJob.getRecruitId());
        if (recruit!=null){
            map.put("id",recruit.getId());
            map.put("headImage",recruit.getHeadImage());   //头像
            map.put("name",recruit.getName());              //姓名
            map.put("phone",recruit.getPhone());            //手机号
            map.put("age",recruit.getAge());                 //年龄
            map.put("stations",recruit.getStations());         //岗位意向
            map.put("marriage",recruit.getMarriage());       //婚姻
            map.put("education",recruit.getEducation());      //学历
            map.put("schoolName",recruit.getSchoolName());  //大学名称
            map.put("major",recruit.getMajor());             //专业
            map.put("passType",recruit.getPassType());    //点评结果
            map.put("score",recruit.getScore());           //点评分数
            map.put("inviteDateTime",recruit.getInviteDateTime()); //面试时间
            map.put("createdAt",recruit.getCreatedAt());  //提交时间
            if (recruit.getEnterType() == 2) {
                map.put("recruitFileUrl", recruit.getRecruitFileUrl());
            }
            map.put("isPassTime",recruit.getIsPassTime());//是否通过时间
            map.put("comment",recruit.getComment());//点评内容
            map.put("enterType", recruit.getEnterType());
            String provinceName = null;
            String cityName = null;
            String countyName = null;
            if (recruit.getProvinceId()!=null){
                provinceName = iDistrictService.getById(recruit.getProvinceId()).getDistrict();
            }
            if (recruit.getCityId()!=null) {
                cityName = iDistrictService.getById(recruit.getCityId()).getDistrict();
            }
            if (recruit.getCountyId()!=null){
                countyName = iDistrictService.getById(recruit.getCountyId()).getDistrict();
            }
            map.put("provinceName",provinceName);
            map.put("cityName",cityName);
            map.put("countyName",countyName);
            //获取证书
            QueryWrapper<RecruitCertificate>  queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("recruit_id", recruit.getId());
            queryWrapper.last("limit 1");
            RecruitCertificate recruitCertificate = iRecruitCertificateService.getOne(queryWrapper);
            if (recruitCertificate != null){
                map.put("certificate",recruitCertificate.getName());   //证书名
                //获取证书图片
                QueryWrapper<RecruitImage>  recruitImageQueryWrapper = new QueryWrapper<>();
                recruitImageQueryWrapper.eq("recruit_id", recruit.getId());
                recruitImageQueryWrapper.eq("recruit_type_id", recruitCertificate.getId());
                List<RecruitImage> recruitImageList = iRecruitImageService.list(recruitImageQueryWrapper);
                if (!recruitImageList.isEmpty()) {
                    List<String> certificateOssImages = new ArrayList<>();
                    for (RecruitImage recruitImage : recruitImageList) {
                        certificateOssImages.add(recruitImage.getOssImage());
                    }
                    map.put("certificateOssImages", certificateOssImages);
                }
            }
            //获取工作经历
            QueryWrapper<RecruitExperience> recruitExperienceQueryWrapper = new QueryWrapper<>();
            recruitExperienceQueryWrapper.eq("recruit_id", recruit.getId());
            recruitExperienceQueryWrapper.last("limit 1");
            RecruitExperience recruitExperience = iRecruitExperienceService.getOne(recruitExperienceQueryWrapper);
            if (recruitExperience != null) {
                map.put("experience", recruitExperience.getContent());  //工作经验
            }
            map.put("created_at",recruit.getCreatedAt());    //提交时间
            if(recruit.getInviterId() != null){
                Staff staff = iStaffService.getById(recruit.getInviterId());
                if (staff != null){
                    map.put("invitationName",staff.getName());  //邀约人
                }
            }
            if(recruit.getEstimateId() != null){
                Staff staff1 = iStaffService.getById(recruit.getEstimateId());
                if (staff1 != null){
                    map.put("estimate",staff1.getName());  //面试官
                }
            }
            Integer type = 0;
            Integer status =0; //1拒绝 2接受
            if (recruit.getStatus()==2 && recruit.getResultStatus() == 2){
                type = 4;
                status = 2;
            }
            //符合（已处理）未邀约
            if (recruit.getStatus()==1 && recruit.getResultStatus() == 0){
                type = 4;
                status = 1;
            }
            //约面试已邀约
            if (recruit.getInterviewStatus() != null) {
                if (recruit.getResultStatus() == 1&& recruit.getInterviewStatus()==1 ){
                    type = 3;
                    status = 1;
                }
                //拒面试中止
                if (recruit.getResultStatus() == 2 && recruit.getInterviewStatus() == 2) {
                    type = 3;
                    status = 2;
                }
            }
            //符合约面试已到
            if (recruit.getIsArrive()!=null) {
                if (recruit.getStatus() == 1 && recruit.getResultStatus() == 1 && recruit.getInterviewStatus() == 1 && recruit.getIsArrive() == 1 ) {
                    type = 5;
                    status = 2;
                }
                //符合约面试未到
                if (recruit.getStatus() == 1 && recruit.getResultStatus() == 2 && recruit.getInterviewStatus() == 1 && recruit.getIsArrive() == 0 ) {
                    type = 5;
                    status = 1;
                }
            }
            RecruitAuditLog recruitAuditLog = iRecruitAuditLogService.selectRecruitAuditLog(status, recruit.getId(), type);
            if (recruitAuditLog != null){
                QueryWrapper<Staff> staffQueryWrapper = new QueryWrapper<>();
                staffQueryWrapper.eq("id", recruitAuditLog.getAuditId());
                staffQueryWrapper.eq("deleted", 0);
                staffQueryWrapper.last("limit 1");
                Staff staff = iStaffService.getOne(staffQueryWrapper);
                if (staff != null) {
                    map.put("auditName", staff.getName());  //获取简历筛选人
                }
            }
        }

        QueryWrapper<EstimateDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("recruit_id", recruit.getId());
        queryWrapper.eq("type", 2);
        long count = iEstimateDetailsService.count(queryWrapper);
        Integer evaluate = 0;//试岗0未评价 1已评价
        if (count > 0){
            evaluate = 1;
        }
        map.put("evaluate",evaluate);
        map.put("assessmentScore",tryJob.getScore());   //专业测评分数
        map.put("subjectsId",tryJob.getSubjectsId());
        map.put("smallScore",tryJob.getSmallScore());
        map.put("trySatisficing",tryJob.getTrySatisficing());
        map.put("tryJobPassType", tryJob.getPassType());
        if (tryJob.getCommentId() != null){
            QueryWrapper<Staff> staffQueryWrapper = new QueryWrapper<>();
            staffQueryWrapper.eq("id", tryJob.getCommentId());
            staffQueryWrapper.eq("deleted", 0);
            staffQueryWrapper.last("limit 1");
            Staff staff = iStaffService.getOne(staffQueryWrapper);
            if (staff != null) {
                map.put("commentName", staff.getName());
            }
        }

        if (tryJob.getPassType() == 1 && tryJob.getIsArriveJob() == 0) {
            map.put("process", "通过");  // 进程 1通过
        } else if (tryJob.getPassType() == 2 && tryJob.getIsArriveJob() == 0) {
            map.put("process", "未通过");  // 进程 2未通过
        } else if (tryJob.getPassType() == 0 && tryJob.getIsAppraisal() == 1 && tryJob.getTrySatisficing() != 0) {
            map.put("process", "未点评-是否通过");
        } else if (tryJob.getPassType() == 0 && (tryJob.getIsAppraisal() == 1 || tryJob.getTrySatisficing() != 0 || (tryJob.getTrySatisficing() == 0 && tryJob.getIsAppraisal() == 0)) && tryJob.getIsArriveJob() == 0) {
            map.put("process", "未点评-待点评");
        } else if(tryJob.getPassType() == 0 && tryJob.getIsArriveJob() == 1){
            map.put("process", "未到岗"); //进程 未到岗
        }

/*        if (tryJob.getPassType() == 1){
            map.put("process", "通过");  //进程 1通过
        }
        if (tryJob.getPassType() == 2){
            map.put("process", "未通过");  //进程 2未通过
        }
        if (tryJob.getPassType() == 0  && tryJob.getIsAppraisal() == 1 && tryJob.getTrySatisficing() != 0){
            map.put("process", "未点评-是否通过");
        }
        if( tryJob.getPassType() == 0 && tryJob.getIsAppraisal() == 1 ){
            map.put("process", "未点评-待点评");
        }
        if (tryJob.getPassType() == 0  && tryJob.getTrySatisficing() != 0){
            map.put("process", "未点评-待点评");
        }
        if (tryJob.getPassType() == 0 && tryJob.getTrySatisficing() == 0 && tryJob.getIsAppraisal() == 0){
            map.put("process", "未点评-待点评");
        }*/
        return new Result(Code.OK, map, Code.GET_OK_MSG);
    }

    @PutMapping("/updateTryJob")
    public Result updateTryJob(@RequestBody TryJob tryJob) {
        TryJob tryJob1 = iTryJobService.getById(tryJob.getId());
        if (tryJob1==null){
            return new Result(Code.ERROR,"","数据不存在");
        }
        Quarter nowQuarter = iQuarterService.getNowQuarter();
        //试岗是否通过
        if (tryJob.getPassType() != null) {
            if (tryJob.getPassType() == 1 || tryJob.getPassType() == 2) {
                tryJob.setTryAuditDate(LocalDateTime.now());
                tryJob.setCommentId(this.adminId);


                //试岗通过推送给运营主管
                //根据校区获取主管
                QueryWrapper<PermissionSchoolTeacher> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("school_id",tryJob1.getSchoolId());
                queryWrapper.eq("type",1);
                queryWrapper.eq("deleted",0);
                queryWrapper.eq("position_type",2);
                queryWrapper.last("limit 1");
                PermissionSchoolTeacher permissionSchoolTeacher = iPermissionSchoolTeacherService.getOne(queryWrapper);

                //推送内容
                Recruit recruit = iRecruitService.getById(tryJob1.getRecruitId());
                String pushTitle = "";
                String pushContent = "";
                if (tryJob.getPassType().equals(1)) {
                    pushTitle = "试岗通过";
                    pushContent = recruit.getName() + "已经试岗通过";

                    /**试岗通过后隔一天自弃开始*/
                    TrialForm trialForm = new TrialForm();
                    trialForm.setTryJobId(tryJob.getId());
                    trialForm.setTrialDate(LocalDate.now().plusDays(1));
                    trialForm.setYearPart(nowQuarter.getYearPart());
                    trialForm.setQuarterNum(nowQuarter.getNum());
                    iTrialFormService.save(trialForm);


                } else if (tryJob.getPassType().equals(2)) {
                    pushTitle = "试岗失败";
                    pushContent = recruit.getName() + "试岗失败";
                }

                if (permissionSchoolTeacher!=null){
                    String typeName;
                    if (tryJob.getPassType() == 1) {
                        typeName = "试岗通过";
                    } else {
                        typeName = "试岗失败";
                    }
                    Staff staff = iStaffService.getById(permissionSchoolTeacher.getTeacherId());
                    if (staff!=null) {
                        if (StringUtils.isNotBlank(staff.getQyWecharId())) {
                            if (recruit!=null) {
                                if (tryJob.getPassType().equals(1)){
                                    pushContent += "，请及时通知该人员加入企业微信架构，并且排班完毕";
                                }
                                //推送给运营主管
                                iQyWeChartPushService.pushMsgRecruit(staff.getQyWecharId(),pushTitle,pushContent,recruit.getId(),3,permissionSchoolTeacher.getTeacherId());

                            }
                        }else {
                            RecruitPushLog log = new RecruitPushLog();
                            log.setRecruitId(tryJob.getRecruitId());
                            log.setType(3); // 3给主管推送试岗通过或者试岗淘汰
                            log.setPushStaffId(permissionSchoolTeacher.getTeacherId());
                            log.setStatus(0); //0未推送
                            log.setRemark(recruit.getName()+typeName+"时"+"qyWecharId为空");
                            iRecruitPushLogService.save(log);

                        }
                    }
                }
                //推送给面试官
                if (StringUtils.isNotBlank(pushTitle)) {
                    iQyWeChartPushService.pushMsgRecruitsDunford(pushTitle,pushContent,recruit.getId(),4);
                }
                //试岗通过或者试岗失败推送给邀约人
                if (recruit.getInviterId() != null) {
                    Staff staff = iStaffService.getById(recruit.getInviterId());
                    if (staff != null) {
                        if (StringUtils.isNotBlank(staff.getQyWecharId())) {
                            //试岗通过或者试岗失败推送给邀约人
                            iQyWeChartPushService.push(staff.getQyWecharId(), pushTitle, pushContent, recruit.getId(), 5, recruit.getInviterId());
                        }
                    }
                }

            }
        }
        //未到岗
        if (tryJob.getIsArriveJob() != null || tryJob.getNotArriveReason() != null){
            tryJob.setNotArriveDate(LocalDateTime.now());
        }
        boolean update = iTryJobService.updateById(tryJob);
        if (update){
            return new Result(Code.UPDATE_OK, "", "操作成功");
        }
        return new Result(Code.UPDATE_ERROR,"","操作失败");
    }

    //试岗弹窗去查看
    /**********该接口作废****************/
    @GetMapping("/getTryJobPopUp")
    public Result getTryJobPopUp() {

        Long adminIdAccount = this.adminId;
        String schoolId = null;
        // 判断是否是超级管理员
        //1667155660271255552L人事主管
        if (adminIdAccount == 1568138350324350975L || adminIdAccount ==1667155660271255552L) {
            return new Result(Code.GET_OK, "", "查询成功");
//            schoolId = null;
        }else {
            List<String> schoolIdByTeacherId = iPermissionSchoolTeacherService.getSchoolIdByTeacherId(String.valueOf(this.adminId));
            if (schoolIdByTeacherId == null || schoolIdByTeacherId.size() ==0){
                return new Result(Code.GET_OK, "", "");

            }
            schoolId = String.join(",", schoolIdByTeacherId);

        }

        List<TryJob> tryJobList = iTryJobService.getTryJobPopUpList(schoolId, this.adminId);

        List<HashMap<String, Object>> list = new ArrayList<>();
        for (TryJob tryJob : tryJobList) {
            HashMap<String, Object> map = new HashMap<>();

            map.put("id", tryJob.getId());
            map.put("tryDate", tryJob.getTryDate());
            map.put("schoolId", tryJob.getSchoolId());
            map.put("schoolName", tryJob.getSchoolName());
            map.put("subjectsId", tryJob.getSubjectsId());
            map.put("recruitId", tryJob.getRecruitId());
            map.put("teacherId", this.adminId);
            list.add(map);
        }
        return new Result(Code.GET_OK, list, "查询成功");
    }

    public  PermissionSchoolTeacher getPermissionSchoolTeacher(Long teacherId){
        QueryWrapper<PermissionSchoolTeacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacher_id", teacherId);
        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("type", 1);
        queryWrapper.last("limit 1");
        PermissionSchoolTeacher permissionSchoolTeacher = iPermissionSchoolTeacherService.getOne(queryWrapper);
        return permissionSchoolTeacher;
    }

    //试岗弹窗去点评
    @GetMapping("/getForceComment")
    public Result getForceComment() {

        Long adminIdAccount = this.adminId;
        String schoolId = null;
        String subjectsId = null;
        // 判断是否是超级管理员
        if (adminIdAccount == 1568138350324350975L || adminIdAccount ==1667155660271255552L) {
            return new Result(Code.GET_OK, "", "查询成功");
        }else {
            //查看校长强制点评
//            List<String> schoolIdByTeacherId = iPermissionSchoolTeacherService.getSchoolIdByTeacherId(String.valueOf(this.adminId));
            List<PermissionSchoolTeacher> permissionSchoolTeacherList = iPermissionSchoolTeacherService.getPermissionSchoolTeacherByTeacherId(String.valueOf(this.adminId));
            List<String> schoolIdByTeacherId = new ArrayList<>();
            List<String> subjectsIdByTeacherId = new ArrayList<>();
            if (permissionSchoolTeacherList != null && permissionSchoolTeacherList.size()>0){
                schoolIdByTeacherId = new ArrayList<>();
                subjectsIdByTeacherId = new ArrayList<>();
                for (PermissionSchoolTeacher permissionSchoolTeacher : permissionSchoolTeacherList) {
                    schoolIdByTeacherId.add(String.valueOf(permissionSchoolTeacher.getSchoolId()));
                    subjectsIdByTeacherId.add(String.valueOf(permissionSchoolTeacher.getSubjectsId()));
                }
            }
            if (schoolIdByTeacherId == null || schoolIdByTeacherId.size() ==0 || subjectsIdByTeacherId == null || subjectsIdByTeacherId.size() ==0){
                return new Result(Code.GET_OK, "", "");

            }
            schoolId = String.join(",", schoolIdByTeacherId);
            subjectsId = String.join(",", subjectsIdByTeacherId);

        }
//        String schoolId = String.join(",", schoolIdByTeacherId);

        // 获取当前日期减去2天的日期
        LocalDate now = LocalDate.now();
//        LocalDate threeDaysAgo = now.minusDays(2); 由原先试岗满2天改为1天
        LocalDate threeDaysAgo = now.minusDays(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDate = threeDaysAgo.format(formatter);
        List<TryJob> forceCommentList = iTryJobService.getForceCommentList(schoolId, subjectsId, formattedDate);
//        QueryWrapper<TryJob> queryWrapperTryJob = new QueryWrapper<>();
//        queryWrapperTryJob.in("school_id", schoolId);
//        queryWrapperTryJob.in("subjects_id", subjectsId);
//        queryWrapperTryJob.eq("pass_type", 0);
//        queryWrapperTryJob.eq("is_arrive_job", 0);
//        queryWrapperTryJob.le("try_date", formattedDate);
//        queryWrapperTryJob.orderByDesc("try_date");
//        List<TryJob> tryJobList = iTryJobService.list(queryWrapperTryJob);
        return new Result(Code.GET_OK, forceCommentList, "查询成功");
    }

    /**
     * 试岗主管强制查看提示
     * @return
     */
    @GetMapping("/getManagerForceView")
    public Result getManagerForceView() {

        Long adminIdAccount = this.adminId;
        String schoolId = null;
        String subjectsId = null;
        // 判断是否是超级管理员
        if (adminIdAccount == 1568138350324350975L || adminIdAccount ==1667155660271255552L) {
            return new Result(Code.GET_OK, "", "查询成功");
        }else {
//            List<String> schoolIdByTeacherId = iPermissionSchoolTeacherService.getManagerByTeacherId(String.valueOf(this.adminId));  //原先
            List<PermissionSchoolTeacher> permissionSchoolTeacherList = iPermissionSchoolTeacherService.getPermissionSchoolTeacherByTeacherId(String.valueOf(this.adminId));
            List<String> schoolIdByTeacherId = new ArrayList<>();
            List<String> subjectsIdByTeacherId = new ArrayList<>();

            if (permissionSchoolTeacherList != null && permissionSchoolTeacherList.size()>0){
              schoolIdByTeacherId = new ArrayList<>();
                for (PermissionSchoolTeacher permissionSchoolTeacher : permissionSchoolTeacherList) {
                    schoolIdByTeacherId.add(String.valueOf(permissionSchoolTeacher.getSchoolId()));
                    subjectsIdByTeacherId.add(String.valueOf(permissionSchoolTeacher.getSubjectsId()));
                }
            }
            if (schoolIdByTeacherId == null || schoolIdByTeacherId.size() ==0 || subjectsIdByTeacherId == null || subjectsIdByTeacherId.size() ==0){
                return new Result(Code.GET_OK, "", "");

            }
            schoolId = String.join(",", schoolIdByTeacherId);
            subjectsId = String.join(",", subjectsIdByTeacherId);

        }

        List<TryJob> tryJobList = iTryJobService.getManagerTryJobPopUpList(schoolId, this.adminId, subjectsId);

        List<HashMap<String, Object>> list = new ArrayList<>();
        for (TryJob tryJob : tryJobList) {
            HashMap<String, Object> map = new HashMap<>();

            map.put("id", tryJob.getId());
            map.put("tryDate", tryJob.getTryDate());
            map.put("schoolId", tryJob.getSchoolId());
            map.put("schoolName", tryJob.getSchoolName());
            map.put("recruitId", tryJob.getRecruitId());
            map.put("subjectsId", tryJob.getSubjectsId());
            map.put("teacherId", this.adminId);

            list.add(map);
        }
        return new Result(Code.GET_OK, list, "查询成功");
    }


    /**
     * 试岗率、试岗通过率
     */
    @GetMapping("/tryJobRate")
    public Result tryJobRate(
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(value = "departmentId", required = false) String departmentId, //部门id
            @RequestParam(value = "stationsId", required = false) String stationsId,  //岗位id，多选，多个逗号隔开
            @RequestParam(value = "labourId", required = false) String labourId,
            @RequestParam(value = "type", defaultValue = "") String type,  //校区招：1， 部门招：2
            @RequestParam(value = "theirType", defaultValue = "") String theirType,  //校区：1， 部门：2
            @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
            @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
            @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
            @RequestParam(value = "dateType", defaultValue = "1") String dateType  //1试岗率 2试岗通过率
    ) {
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            startDate = startDate + " 00:00:00";
            endDate = endDate + " 23:59:59";
        }
        List<RecruitList> recruitList = iTryJobService.tryJobRate(startDate, endDate, departmentId, stationsId, labourId, type, yearPart, quarterNum, dateType, theirType, subjectsId);

        return new Result(Code.OK, recruitList, Code.GET_OK_MSG);
    }


    /**
     * 试岗率、试岗通过率详情
     *
     * @param startDate
     * @param endDate
     * @param departmentId
     * @param stationsId
     * @param labourId
     * @param type
     * @param inviterId
     */
    @GetMapping("/tryJobRateDetails")
    public Result tryJobRateDetails(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(value = "departmentId", required = false) String departmentId, //部门id
            @RequestParam(value = "stationsId", required = false) String stationsId,  //岗位id，多选，多个逗号隔开
            @RequestParam(value = "labourId", required = false) String labourId,
            @RequestParam(value = "type", defaultValue = "") String type,  //校区招：1， 部门招：2
            @RequestParam(value = "theirType", defaultValue = "") String theirType,  //校区：1， 部门：2
            @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
            @RequestParam(value = "inviterId", required = false) String inviterId,
            @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
            @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
            @RequestParam(value = "dateType", defaultValue = "1") String dateType, //1试岗率 2试岗通过率
            @RequestParam(value = "recruitStatus", defaultValue = "0") String recruitStatus //0面试通过，1未到岗，2已试岗，3面试岗人数 4试岗通过 5试岗自弃 6试岗淘汰
    ) {
        Page<Recruit> iPage = new Page<>(pageNum, pageSize);
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            startDate = startDate + " 00:00:00";
            endDate = endDate + " 23:59:59";
        }
        iTryJobService.tryJobRateDetails(iPage, startDate, endDate, departmentId, stationsId, labourId, type, inviterId, yearPart, quarterNum, dateType, recruitStatus, theirType, subjectsId);
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }

}
